package com.innovation.ic.sc.web.schedule;

import com.innovation.ic.sc.base.model.erp9_pvestandard.Brands;
import com.innovation.ic.sc.base.model.sc.Brand;
import com.innovation.ic.sc.base.pojo.constant.handler.RedisStorage;
import com.innovation.ic.sc.base.pojo.variable.ServiceResult;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;


/**
 * 定时同步品牌到sc
 */
@Component
@Slf4j
public class ImportBrandsSchedule extends AbstractSchedule {


    //@Scheduled(cron = " 15 * * * * ?")
//    @XxlJob("importBrandsJob")
    private void importBrands() {
        try {
            List<Brands> erpBrands = brandsService.selectAllBrands();
            if (CollectionUtils.isEmpty(erpBrands)) {
                return;
            }
            brandService.truncate();
            brandService.insertBatch(erpBrands);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("定时更新品牌表出错:", e);
        }
    }

    @XxlJob("importInitBrandsToRedisJob")
    private void importInitBrandsToRedis() {
        try {
            // 查找brand表中所有记录
            ServiceResult<List<Brand>> serviceResult = brandService.findAll();
            if (null != serviceResult && null != serviceResult.getResult()) {
                String keyAsc = RedisStorage.TABLE + RedisStorage.BRAND +
                        RedisStorage.CREATE_DATE_ASC;
                String keyDesc = RedisStorage.TABLE + RedisStorage.BRAND +
                        RedisStorage.CREATE_DATE_DESC;

                // 删除旧的数据
                serviceHelper.getRedisManager().del(keyAsc);
                serviceHelper.getRedisManager().del(keyDesc);

                // 向redis中导入数据
                List<Brand> brandList = serviceResult.getResult();
                for (int i = 0; i < brandList.size(); i++) {
                    Brand brand = brandList.get(i);
                    String value = modelHandler.brandToXmlStorageString(brand);
                    serviceHelper.getRedisManager().zAdd(keyAsc, value, brand.getCreateDate().getTime());
                    serviceHelper.getRedisManager().zAdd(keyDesc, value, -brand.getCreateDate().getTime());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("定时更新品牌表出错:", e);
        }
    }
}